<?php
/**
 * All of actions related to money will be listed here
 * @author DatNgo <nhdat.itec@gmai.com>
 * @create_at   29 Jun, 2013
 * @updated     <name>
 * @updated_at  <time>
 */
class BankController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			)
		);
	}
	
    public function actionDeposit()
    {
        $type = isset($_GET['type'])?$_GET['type']:'';
        if(!array_key_exists($type, Transaction::getType())) {
        	$this->redirect($this->baseUrl);
        }
        $model = new Deposit();
        $model->type = $type;
        if(!empty($this->curr_user)) {
        	$model->code_deposit = $this->curr_user['code'];
        }
        $this->validateAjax($model);
    	if(isset($_POST['Deposit'])){
			$model->setAttributes($_POST['Deposit'], false);
			if($model->validate()){
				//Save SESSION for deposit
				$time = time();
				$whoReceive = '';
				if($type == 'wmz') {
					$account = AccountWMZReceive();
					$whoReceive = $account['payeePurse'];
				}else if($type == 'pm') {
					$account = AccountPMReceive();
					$whoReceive = $account['acc'];
				}else if($type == 'bk') {
					$account = AccountBKReceive();
					$whoReceive = $account['acc'];
				}else if($type == 'nl') {
					$account = AccountNLReceive();
					$whoReceive = $account['acc'];
				}
				$amount_transfer = $model->amount_transfer;
				$min = Setting::getValueSetting('deposit', $type);
				if($amount_transfer<$min) $this->redirect($this->baseUrl);
				$fee = 0;
	    		if($type == 'bk') $fee = 0.01;
	    		if($type == 'nl') $fee = 0.01;
	    		if($type == 'pm') $fee = 0.005;
	    		if($type == 'wmz') $fee = 0.008;
	    		$you_need_have = ($amount_transfer + ($amount_transfer*$fee));
	    		if($type != 'bk' && $type != 'nl') $you_need_have = round($you_need_have, 2);
	    		//Coin will receice
	    		$rate = Currency::getValueCurrency($type);
	    		$coin_receive = $amount_transfer * $rate;
	    		//amount payment
	    		if($type == 'wmz' || $type == 'pm') {
					$expl = explode('.', $amount_transfer);
					$amount_new = $amount_transfer;
					if(count($expl)==2)
					{
						if(strlen($expl[1])==1)
						{
							$amount_new = $expl[0].".".$expl[1]."0";
						}
					}else{
						$amount_new = $amount_transfer.".00";
					}
					$amount_transfer = $amount_new;
	    		}
	    		//Check code exist on system
	    		$modelUser = User::model()->findByAttributes(array('code'=>$model->code_deposit));
	    		if(!is_object($modelUser)) $this->redirect($this->baseUrl);
				$hash = strtoupper(hash('sha256', $whoReceive.'__'.$amount_transfer.'__'.$time.'__payment='.$type.'!@#$%^&*()_+'));
				$deposit = array(
					'type'=>$model->type,
					'amount_transfer'=>$amount_transfer,
					'you_need_have'=>$you_need_have,
					'amount_receive'=>$coin_receive,
					'rate'=>$rate,
					'code_deposit'=>$model->code_deposit,
					'hash'=>$hash,
					'time'=>$time
				);
				Yii::app()->session->add('deposit',$deposit);
				$this->redirect($this->createUrl('bank/payment'));
			}
		}
    	$this->render('deposit',
    		array(
    			'type'=>$type,
    			'model'=>$model
    		)
    	);
    }
    
    /**
     * Start payment
     */
    public function actionPayment() {
    	if(!Yii::app()->session->get('deposit')) {
    		$this->redirect($this->baseUrl);
    	}
    	$deposit = Yii::app()->session->get('deposit');
    	$this->render('payment',
    		array(
    			'deposit'=>$deposit
    		)
    	);
    }
    
	/**
	 * Fail Payment
	 */
	public function actionFailPayment() {
		$this->render('fail');
	}
	
	/**
	 * Success Payment
	 */
	public function actionsuccessPayment() {
		$this->render('success');
	}
	
	/**
	 * Success PM
	 */
	public function actionSuccessPM() {
		if(!Yii::app()->session->get('deposit')) {
    		$this->redirect($this->baseUrl);
    	}
		$deposit = Yii::app()->session->get('deposit');
		$amount = $deposit['amount_transfer'];
		$account_pm = AccountPMReceive();
		$ALTERNATE_PHRASE_HASH=strtoupper(md5($account_pm['security']));
		$string=
		      @$_POST['PAYMENT_ID'].':'.@$_POST['PAYEE_ACCOUNT'].':'.
		      @$_POST['PAYMENT_AMOUNT'].':'.@$_POST['PAYMENT_UNITS'].':'.
		      @$_POST['PAYMENT_BATCH_NUM'].':'.
		      @$_POST['PAYER_ACCOUNT'].':'.$ALTERNATE_PHRASE_HASH.':'.
		      @$_POST['TIMESTAMPGMT'];
		$hashPM=strtoupper(md5($string));
		$hash = strtoupper(hash('sha256', $_POST['PAYEE_ACCOUNT'].'__'.$_POST['PAYMENT_AMOUNT'].'__'.$deposit['time'].'__payment=pm!@#$%^&*()_+'));
		if($hash != $deposit['hash'] || $hashPM != $_POST['V2_HASH']) {
			$this->redirect($this->baseUrl.'/bank/failPayment');
		}
		if($_POST['PAYMENT_AMOUNT']==$amount && $_POST['PAYEE_ACCOUNT']==$account_pm['acc'] && $_POST['PAYMENT_UNITS']=='USD'){
			$deposit['payer'] = $_POST['PAYER_ACCOUNT'];
			Transaction::model()->successPayment($deposit);
			Yii::app()->session->remove('deposit');
			Yii::app()->session->add('coin_deposit', number_format($deposit['amount_receive'], 0, ',','.'));
			$this->redirect($this->baseUrl.'/bank/successPayment');
		}else{
			$this->redirect($this->baseUrl.'/bank/failPayment');
	    }
	}
	
	/**
	 * Success WMZ
	 */
	public function actionsuccessWMZ() {
		$account_wmz = AccountWMZReceive();
		$payeePurse = $account_wmz['payeePurse'];
		$wmSecretKey = $account_wmz['wmSecretKey'];
		
		if(!Yii::app()->session->get('deposit')) {
    		$this->redirect($this->baseUrl);
    	}
		$deposit = Yii::app()->session->get('deposit');
		$amount = $deposit['amount_transfer'];
		$lmi_payee_purse = $_POST['LMI_PAYEE_PURSE'];
		$lmi_payment_amount = $_POST['LMI_PAYMENT_AMOUNT'];
		$lmi_payment_no = $_POST['LMI_PAYMENT_NO'];
		$lmi_mode = $_POST['LMI_MODE'];
		$lmi_sys_invs_no = $_POST['LMI_SYS_INVS_NO'];
		$lmi_sys_trans_no = $_POST['LMI_SYS_TRANS_NO'];
		$lmi_payer_purse = $_POST['LMI_PAYER_PURSE'];
		$lmi_payer_wm = $_POST['LMI_PAYER_WM'];
		$lmi_hash = $_POST['LMI_HASH'];
		$lmi_sys_trans_date = $_POST['LMI_SYS_TRANS_DATE'];
		
		$hash = strtoupper(hash('sha256', $lmi_payee_purse.'__'.$lmi_payment_amount.'__'.$deposit['time'].'__payment=wmz!@#$%^&*()_+'));
		if($hash != $deposit['hash']) {
			$this->redirect($this->baseUrl.'/bank/failPayment');
		}
		
		$sing_hash_str = 
				$lmi_payee_purse.
				$lmi_payment_amount.
				$lmi_payment_no.
				$lmi_mode.
				$lmi_sys_invs_no.
				$lmi_sys_trans_no.
				$lmi_sys_trans_date.
				$wmSecretKey.
				$lmi_payer_purse.
				$lmi_payer_wm;
		$sign_hash = strtoupper(md5($sing_hash_str));
		if(!empty($lmi_payee_purse) && !empty($lmi_payment_amount) &&
		!empty($lmi_sys_invs_no) && !empty($lmi_sys_trans_no) && 
		!empty($lmi_payer_wm) && !empty($lmi_payer_purse) && !empty($lmi_hash) && 
		!empty($lmi_sys_trans_date) && ($payeePurse === $lmi_payee_purse) ){
			$sing_hash_str = 
				$lmi_payee_purse.
				$lmi_payment_amount.
				$lmi_payment_no.
				$lmi_mode.
				$lmi_sys_invs_no.
				$lmi_sys_trans_no.
				$lmi_sys_trans_date.
				$wmSecretKey.
				$lmi_payer_purse.
				$lmi_payer_wm;
			$sign_hash = strtoupper(md5($sing_hash_str));
			if(($sign_hash === $lmi_hash) && ($lmi_mode == 0) && ($lmi_payment_amount == $amount)){
				$deposit['payer'] = $lmi_payer_purse;
				Transaction::model()->successPayment($deposit);
				Yii::app()->session->remove('deposit');
				Yii::app()->session->add('coin_deposit', number_format($deposit['amount_receive'], 0, ',','.'));
				$this->redirect($this->baseUrl.'/bank/successPayment');
			}else{
				$this->redirect($this->baseUrl.'/bank/failPayment');
			}
		}else{
		  	$this->redirect($this->baseUrl.'/bank/failPayment');
		}
	}
	
	/**
	 * Success Bao Kim
	 */
	public function actionsuccessBK() {
		if(!Yii::app()->session->get('deposit')) {
    		$this->redirect($this->baseUrl);
    	}
    	$deposit = Yii::app()->session->get('deposit');
		$baokim = new BaoKimPayment();
		$validate = $baokim->verifyResponseUrl($_GET);
		Yii::app()->session->remove('deposit');
		if ($validate){
			$deposit['payer'] = $_GET["customer_email"];
			Transaction::model()->successPayment($deposit);
			Yii::app()->session->remove('deposit');
			Yii::app()->session->add('coin_deposit', number_format($deposit['amount_receive'], 0, ',','.'));
			$this->redirect($this->baseUrl.'/bank/successPayment');
		}else{
			$this->redirect($this->baseUrl.'/bank/failPayment');
		}
	}
	
	/**
	 * Success Ngan Luong
	 */
	public function actionsuccessNL() {
		if(!Yii::app()->session->get('deposit')) {
    		$this->redirect($this->baseUrl);
    	}
    	$deposit = Yii::app()->session->get('deposit');
		//Lấy thông tin giao dịch
		$transaction_info=@$_GET["transaction_info"];
		//Lấy mã đơn hàng 
		$order_code=@$_GET["order_code"];
		//Lấy tổng số tiền thanh toán tại ngân lượng 
		$price=@$_GET["price"];
		//Lấy mã giao dịch thanh toán tại ngân lượng
		$payment_id=@$_GET["payment_id"];
		//Lấy loại giao dịch tại ngân lượng (1=thanh toán ngay ,2=thanh toán tạm giữ)
		$payment_type=@$_GET["payment_type"];
		if($payment_type!=1)
		{
			Yii::app()->session->remove('deposit');
			$this->redirect($this->baseUrl.'/bank/failPayment');
		}
		//Lấy thông tin chi tiết về lỗi trong quá trình giao dịch
		$error_text=@$_GET["error_text"];
		//Lấy mã kiểm tra tính hợp lệ của đầu vào 
		$secure_code=@$_GET["secure_code"];
		
		//Xử lí đầu vào 
		$nganluong = new NganLuongPayment();
		$validate= $nganluong->verifyPaymentUrl($transaction_info, $order_code, $price, $payment_id, $payment_type, $error_text, $secure_code);
		Yii::app()->session->remove('deposit');
		if ($validate){
			$deposit['payer'] = $_GET["customer_email"];
			Transaction::model()->successPayment($deposit);
			Yii::app()->session->remove('deposit');
			Yii::app()->session->add('coin_deposit', number_format($deposit['amount_receive'], 0, ',','.'));
			$this->redirect($this->baseUrl.'/bank/successPayment');
		}else{
			$this->redirect($this->baseUrl.'/bank/failPayment');
		}
	}
    
    /**
     * 
     * Caculator amount transfer from deposit
     */
    public function actionamountTransfer() {
    	if(Yii::app()->request->isAjaxRequest) {
    		$amount = isset($_GET['amount'])?$_GET['amount']:0;
    		if($amount<=0) return;
    		$type = isset($_GET['type'])?$_GET['type']:'';
    		if(!in_array($type, array('wmz', 'pm', 'bk', 'nl'))) return;
    		$min = Setting::getValueSetting('deposit', $type);
			if($min) {
				if($amount < $min) {
					return '-1';
				}
			}
    		$fee = 0;
    		if($type == 'bk') $fee = 0.01;
    		if($type == 'nl') $fee = 0.01;
    		if($type == 'pm') $fee = 0.005;
    		if($type == 'wmz') $fee = 0.008;
    		$you_need_have = ($amount + ($amount*$fee));
    		if($type != 'bk' && $type != 'nl') $you_need_have = round($you_need_have, 2);
    		else $you_need_have = number_format($you_need_have, 0, ',', '.');
    		//Coin will receice
    		$rate = Currency::getValueCurrency($type);
    		$coin_receive = $amount * $rate;
    		$coin_receive = number_format($coin_receive, 0, ',', '.');
    		echo json_encode(array('you_need_have'=>$you_need_have, 'coin_receive'=>$coin_receive));
    		return;
    	}
    }

    public function actionlistDeposits(){
    	$this->render("list_payment");
    }


    public function actionTransfer(){
    	if(Yii::app()->user->isGuest){
    		$this->redirect(array('user/login'));
    	}
		$min_transfer = Setting::model()->getValueSetting('setting','min_transfer');
		$transfer_rate = Setting::model()->getValueSetting('setting','transfer_rate');
    	$model = new TransferForm();
    	$this->validateAjax($model);
    	if(Yii::app()->request->isPostRequest && !empty($_POST['TransferForm'])){
    		$model->setAttributes($_POST['TransferForm']);
    		if($model->validate()){
    			$result = Transaction::model()->transfer($model->to, $model->amount, $transfer_rate);
    			if($result){

    			}
    		}
    	}
    	$this->render('transfer', array(
    		'model' => $model,
    		'min_transfer' => $min_transfer,
    		'transfer_rate'=> $transfer_rate
    	));
    }

    public function actionTransferFail(){
    	$this->render('transferfail');
    }

    public function actionConfirmTransfer($code, $tran_code){
    	$status ="";
    	if(empty($code) || empty($tran_code) || !is_string($tran_code)){
    		$this->redirect('transferFail');
    	}
    	$model = Transaction::model()->findByAttributes(array('code' => $code, 'tran_cert' => $tran_code,'archived' => false));
    	if(!is_object($model)){
    		$this->redirect('transferFail');
    	}
    	if(Yii::app()->request->isPostRequest){
    		if(isset($_POST['destroy'])){
    			$result = $model->delete();
    			if($result){
    				$status = "destroy";
    			}else{
    				$this->redirect('transferFail');
    			}
    		}else{
    			$result = $model->confirmTransfer();
    			if($result){
    				$status = "transfer";
    			}
    		}
    	}
    	$this->render('confirm_transfer', array(
    		'model' => $model,
    		'status' => $status
    	));
    }

}